package com.yao.component.pictureselector;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

//import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
//import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
//import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
//import com.nostra13.universalimageloader.core.*;
//import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
//import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
//import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
//import com.nostra13.universalimageloader.utils.StorageUtils;
import com.yao.component.pictureselector.adapter.ImgGrideAdapter;
import com.yao.component.pictureselector.bean.ImageFloder;


public class PhotoBrowseActivity extends BaseActivity implements OnClickListener
{
	/**
	 * 用户选择的图片，存储为图片的完整路径
	 */
	public  static  int maxSelectCount=9;
	public static ArrayList<String> mSelectedImage = new ArrayList<>();
	private AlertDialog mProgressDialog;
	private LinearLayout finish;
	/**
	 * 存储文件夹中的图片数量
	 */
	private int mPicsSize;
	/**
	 * 图片数量最多的文件夹
	 */
	private File mImgDir;
	/**
	 * 所有的图片
	 */
	private ArrayList<String> mImgs;
//	private ArrayList<String> allImgs=new ArrayList<>();
	private GridView mGirdView;
	private ImgGrideAdapter mAdapter;
	/**
	 * 临时的辅助类，用于防止同一个文件夹的多次扫描
	 */
	private HashSet<String> mDirPaths = new HashSet<String>();

	/**
	 * 扫描拿到所有的图片文件夹
	 */
	public static List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();

//	private RelativeLayout mBottomLy;

	private TextView preview,finish_tv;
	private TextView select_count;
	int totalCount = 0;
	private UpDataReciver reciver;
	private int mScreenHeight;
	private boolean isSingle;


	private Handler mHandler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			mProgressDialog.dismiss();
			// 为View绑定数据
			data2View();
			// 初始化展示文件夹的popupWindw
//			initListDirPopupWindw();
		}
	};

	/**
	 * 为View绑定数据
	 */
	private void data2View()
	{
		if (totalCount == 0)
		{
			Toast.makeText(getApplicationContext(), "未查找到图片",
					Toast.LENGTH_SHORT).show();
			return;
		}
		showLeftTv("更多",new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent=new Intent(PhotoBrowseActivity.this,ImageDirActivity.class);
				startActivityForResult(intent,1);
			}
		});
		File[] files=mImgDir.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String filename) {
				// TODO Auto-generated method stub
				if (filename.endsWith(".jpg") || filename.endsWith(".png")
						|| filename.endsWith(".jpeg")||filename.endsWith(".gif"))
					return true;
				return false;
			}
		});
		mImgs=new ArrayList<String>();
		for (int i = 0; i < files.length; i++) {
			mImgs.add(files[i].getAbsolutePath());
		}
		/**
		 * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
		 */
		mAdapter = new ImgGrideAdapter(PhotoBrowseActivity.this, mImgs,
				R.layout.img_grid_item,isSingle);
		mAdapter.setOnPictureClickListener(new ImgGrideAdapter.onPictureClickListener() {
			@Override
			public void onAddPicture(String path) {
				if (!mSelectedImage.contains(path)){
					mSelectedImage.add(path);
					showSelectCount();
				}

			}

			@Override
			public void onRemovePicture(String path) {
				if (mSelectedImage.contains(path)){
					mSelectedImage.remove(path);
					showSelectCount();
				}
			}
		});
		mGirdView.setAdapter(mAdapter);
		showTitle(mImgDir.getName());

	};



	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_img_browse);
		showRightTv("取消", new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSelectedImage.clear();
				returnResult();

			}
		});

		int maxCount=getIntent().getIntExtra("MAX_COUNT",-1);
		isSingle=getIntent().getBooleanExtra("IS_SINGLE",false);
		if (maxCount!=-1){
			maxSelectCount=maxCount;
		}else {
			maxSelectCount=9;
		}

//		initImageLoader();
		initView();
		getImages();

		IntentFilter filter=new IntentFilter();
		filter.addAction("com.yao.component.pictureselector.selectupdata");
		reciver=new UpDataReciver();
		registerReceiver(reciver,filter);
//		initEvent();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(reciver);
	}

	@Override
	protected void onResume() {
		super.onResume();
		showSelectCount();
//		if (mAdapter!=null){
//			mAdapter.notifyDataSetChanged();
//		}
	}
	public void showSelectCount(){
		if (mSelectedImage.size()>0){
			select_count.setVisibility(View.VISIBLE);
			select_count.setText(mSelectedImage.size()+"");
			preview.setTextColor(getResources().getColor(R.color.black));
			finish_tv.setTextColor(getResources().getColor(R.color.bg_red));
		}else {
			select_count.setVisibility(View.GONE);
			preview.setTextColor(getResources().getColor(R.color.text_hint_gray));
			finish_tv.setTextColor(getResources().getColor(R.color.bg_red_tran));
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

			if (requestCode==1){
				mSelectedImage.clear();
				if (resultCode==RESULT_OK){

				selected(mImageFloders.get(data.getIntExtra("position",0)));
				}else if (resultCode==RESULT_CANCELED){
					returnResult();

				}
			}else if (requestCode==2){
				if (resultCode==RESULT_OK){
					returnResult();
				}
			}

	}

	/**
	 * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中 完成图片的扫描，最终获得jpg最多的那个文件夹
	 */
	private void getImages()
	{
//		if (!Environment.getExternalStorageState().equals(
//				Environment.MEDIA_MOUNTED))
//		{
//			Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
//			mSelectedImage.clear();
//			returnResult();
//			return;
//		}
		mProgressDialog=new AlertDialog.Builder(this).create();

		mProgressDialog.show();
		mProgressDialog.setContentView(LayoutInflater.from(this).inflate(R.layout.progress_dialog,null));

		mImageFloders.clear();
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{

				String firstImage = null;

				Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = PhotoBrowseActivity.this
						.getContentResolver();

				// 只查询jpeg和png的图片
				Cursor mCursor = mContentResolver.query(mImageUri, null,
						MediaStore.Images.Media.MIME_TYPE + "=? or "
								+ MediaStore.Images.Media.MIME_TYPE + "=? or "
								+MediaStore.Images.Media.MIME_TYPE + "=?",
						new String[] { "image/jpeg", "image/png","image/gif" },
						MediaStore.Images.Media.DATE_MODIFIED);

				Log.e("TAG", mCursor.getCount() + "");
				while (mCursor.moveToNext())
				{
					// 获取图片的路径
					String path = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.DATA));

					// 拿到第一张图片的路径
					if (firstImage == null)
						firstImage = path;
					// 获取该图片的父路径名
					File parentFile = new File(path).getParentFile();
					if (parentFile == null)
						continue;
					String dirPath = parentFile.getAbsolutePath();
					ImageFloder imageFloder = null;
					// 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
					if (mDirPaths.contains(dirPath))
					{
						continue;
					} else
					{
						mDirPaths.add(dirPath);
						File file=new File(dirPath);
						String[] lists=file.list();
						if (lists==null){
							continue;
						}
						System.out.println(lists);
						// 初始化imageFloder
						imageFloder = new ImageFloder();
						imageFloder.setDir(dirPath);
						imageFloder.setFirstImagePath(path);
					}
					int picSize = parentFile.list(new FilenameFilter()
					{
						@Override
						public boolean accept(File dir, String filename)
						{
							if (filename.endsWith(".jpg")
									|| filename.endsWith(".png")
									|| filename.endsWith(".jpeg")
									||filename.endsWith(".gif"))
								return true;
							return false;
						}
					}).length;
					totalCount+=picSize;

					imageFloder.setCount(picSize);
					mImageFloders.add(imageFloder);

					if (picSize > mPicsSize)
					{
						mPicsSize = picSize;
						mImgDir = parentFile;
					}
				}
				mCursor.close();
				mDirPaths = null;
				mHandler.sendEmptyMessage(0x110);

			}
		}).start();

	}

	/**
	 * 初始化View
	 */
	private void initView()
	{
		finish=(LinearLayout)findViewById(R.id.finish);
		finish.setOnClickListener(this);
		mGirdView = (GridView) findViewById(R.id.id_gridView);
		preview = (TextView) findViewById(R.id.preview);
		preview.setOnClickListener(this);
		select_count = (TextView) findViewById(R.id.select_count);
		finish_tv=(TextView) findViewById(R.id.finish_tv);
//		mBottomLy = (RelativeLayout) findViewById(R.id.id_bottom_ly);
		if (isSingle){
			findViewById(R.id.id_bottom_ly).setVisibility(View.GONE);
		}else {
			findViewById(R.id.id_bottom_ly).setVisibility(View.VISIBLE);
		}
		mGirdView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (!isSingle){
					Intent intent=new Intent(PhotoBrowseActivity.this,PhotoPreviewActivity.class);
					intent.putStringArrayListExtra("paths",mImgs);
					intent.putExtra("position",position);
					startActivityForResult(intent,2);
				}else {
					mSelectedImage.add(mImgs.get(position));
					returnResult();
				}


			}
		});
	}

//	private void initEvent()
//	{
//		/**
//		 * 为底部的布局设置点击事件，弹出popupWindow
//		 */
//		mBottomLy.setOnClickListener(new OnClickListener()
//		{
//			@Override
//			public void onClick(View v)
//			{
//				mListImageDirPopupWindow
//						.setAnimationStyle(R.style.anim_popup_dir);
//				mListImageDirPopupWindow.showAsDropDown(mBottomLy, 0,0);
//				// 设置背景颜色变暗
//				WindowManager.LayoutParams lp = getWindow().getAttributes();
//				lp.alpha = .3f;
//				getWindow().setAttributes(lp);
//			}
//		});
//	}

	public void selected(ImageFloder floder)
	{
//		if (floder.getName().equals("所有图片")){
//			mAdapter = new MyAdapter(getApplicationContext(), allImgs,
//					R.layout.img_grid_item);
//		}else{
			mImgDir = new File(floder.getDir());
			File[] files=mImgDir.listFiles(new FilenameFilter() {

				@Override
				public boolean accept(File dir, String filename) {
					// TODO Auto-generated method stub
					if (filename.endsWith(".jpg") || filename.endsWith(".png")
							|| filename.endsWith(".jpeg")||filename.endsWith(".gif"))
						return true;
					return false;
				}
			});
			mImgs=new ArrayList<String>();
			for (int i = 0; i < files.length; i++) {
				mImgs.add(files[i].getAbsolutePath());
			}
			mAdapter = new ImgGrideAdapter(PhotoBrowseActivity.this, mImgs,
					R.layout.img_grid_item,isSingle);
		mAdapter.setOnPictureClickListener(new ImgGrideAdapter.onPictureClickListener() {
			@Override
			public void onAddPicture(String path) {
				if (!mSelectedImage.contains(path)){
					mSelectedImage.add(path);
					showSelectCount();
				}

			}

			@Override
			public void onRemovePicture(String path) {
				if (mSelectedImage.contains(path)){
					mSelectedImage.remove(path);
					showSelectCount();
				}
			}
		});


		mGirdView.setAdapter(mAdapter);
		// mAdapter.notifyDataSetChanged();
//		mImageCount.setText(floder.getCount() + "张");
		showTitle(mImgDir.getName());
//		mListImageDirPopupWindow.dismiss();

	}
//	private void initImageLoader() {
//		DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
//				.showImageOnLoading(R.drawable.ic_picture_loading)
//				.showImageOnFail(R.drawable.ic_picture_loadfailed)
//				.cacheInMemory(true).cacheOnDisk(true)
//				.resetViewBeforeLoading(true).considerExifParams(false)
//				.bitmapConfig(Bitmap.Config.RGB_565).build();
//
//		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
//				this)
//				.memoryCacheExtraOptions(400, 400)
//				// default = device screen dimensions
//				.diskCacheExtraOptions(400, 400, null)
//				.threadPoolSize(5)
//				// default Thread.NORM_PRIORITY - 1
//				.threadPriority(Thread.NORM_PRIORITY)
//				// default FIFO
//				.tasksProcessingOrder(QueueProcessingType.LIFO)
//				// default
//				.denyCacheImageMultipleSizesInMemory()
//				.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
//				.memoryCacheSize(2 * 1024 * 1024)
//				.memoryCacheSizePercentage(13)
//				// default
//				.diskCache(
//						new UnlimitedDiscCache(StorageUtils.getCacheDirectory(
//								this, true)))
//				// default
//				.diskCacheSize(50 * 1024 * 1024).diskCacheFileCount(100)
//				.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
//				// default
//				.imageDownloader(new BaseImageDownloader(this))
//				// default
//				.imageDecoder(new BaseImageDecoder(false))
//				// default
//				.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
//				// default
//				.defaultDisplayImageOptions(imageOptions).build();
//
//		com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
//	}

	@Override
	public void onClick(View v) {
		int id=v.getId();
		if (id==R.id.finish){
			if (mSelectedImage.size()>0){
				returnResult();
			}
		}else if(id==R.id.preview){
			if (mSelectedImage.size()>0){
				Intent intent=new Intent(PhotoBrowseActivity.this,PhotoPreviewActivity.class);
				intent.putStringArrayListExtra("paths",mSelectedImage);
				intent.putExtra("position",0);
				startActivityForResult(intent,2);
			}
		}
//		switch (v.getId()){
//			int id=v.getId();
//			case  R.id.finish:
//				if (mSelectedVideo.size()>0){
//					returnResult();
//				}
//				break;
//			case R.id.preview:
//				if (mSelectedVideo.size()>0){
//					Intent intent=new Intent(PhotoBrowseActivity.this,PhotoPreviewActivity.class);
//					intent.putStringArrayListExtra("paths",mSelectedVideo);
//					intent.putExtra("position",0);
//					startActivityForResult(intent,2);
//				}
//				break;
//		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		mSelectedImage.clear();
		returnResult();
	}
	public void returnResult(){
		Intent intent = new Intent();
		intent.setAction("com.yao.component.pictureselector.selectimage");
		intent.putStringArrayListExtra("select_image", mSelectedImage);
		PhotoBrowseActivity.this.sendBroadcast(intent);
		PhotoBrowseActivity.this.finish();
	}
	class UpDataReciver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			if (mAdapter!=null){
				mAdapter.notifyDataSetChanged();
			}
		}
	}
}
